package cn.aiweiyi.qingjing.coupon.template.service.impl;

import cn.aiweiyi.qingjing.coupon.comm.exception.CouponException;
import cn.aiweiyi.qingjing.coupon.template.dao.CouponTemplateDao;
import cn.aiweiyi.qingjing.coupon.template.entity.CouponTemplate;
import cn.aiweiyi.qingjing.coupon.template.service.TemplateBaseService;
import cn.aiweiyi.qingjing.coupon.comm.vo.CouponTemplateSDK;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 青衿
 * @Date 2020/11/17 10:26
 * 模板基础方法实现类
 **/
@Slf4j
@Service
public class TemplateBaseServiceImpl implements TemplateBaseService {
    @Resource
    CouponTemplateDao couponTemplateDao;

    //根据模板id获得模板信息
    @Override
    public CouponTemplate findTemplateInfo(Integer tid) throws CouponException {
//       Optional封装是为了尽量避免空指针异常,;配合函数式编程上
        Optional<CouponTemplate> template = couponTemplateDao.findById(tid);
        if (!template.isPresent()) {
            throw new CouponException("模板不存在:" + tid);
        }
        return template.get();
    }

    @Override
    public List<CouponTemplateSDK> findAllUsableTemplate() {
        List<CouponTemplate> templates = couponTemplateDao.findAllByAvailableAndExpired
                (true, false);
        List<CouponTemplateSDK> templateSDKS
                = new ArrayList<>();
        //Java / Lambda编码风格
        //for循环中把每个对象传入template2TemplateSDK转换,
        //然后加入到templateSDKS集合中
        templates.forEach(t ->
                templateSDKS.add(template2TemplateSDK(t)));
        //或
        //return templates.stream().map(this::template2TemplateSDK)
        //.collect(Collectors.toList());
        return templateSDKS;
    }

    //根据一批id查询Coupon
    @Override
    public Map<Integer, CouponTemplateSDK> findIds2TemplateSDK(Collection<Integer> ids) {
        List<CouponTemplate> templates = couponTemplateDao.findAllById(ids);
        Map<Integer, CouponTemplateSDK> map = new HashMap<>();
        for (CouponTemplate t : templates) {
            CouponTemplateSDK cts = template2TemplateSDK(t);
            map.put(cts.getId(), cts);
        }
        return map;
    }

    private CouponTemplateSDK template2TemplateSDK(CouponTemplate template) {
        return new CouponTemplateSDK(
                template.getId(),
                template.getName(),
                template.getLogo(),
                template.getDesc(),
                template.getCategory().getCode(),
                template.getProductLine().getCode(),
                template.getKey(),//并不是拼装好的 Template Key
                template.getTarget().getCode(),
                template.getRule());
    }
}
